import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponse } from '../interface/response.interface';
import { HttpStatusCodeEnum } from '../enums/http-status-code.enum'; // 导入统一响应格式
import { HttpStatusMessages } from '../utils/http-message.util';

@Injectable()
export class ResponseInterceptor<T>
  implements NestInterceptor<T, ApiResponse<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ApiResponse<T>> {
    return next.handle().pipe(
      map((data) => {
        return {
          status: HttpStatusCodeEnum.OK,
          message: HttpStatusMessages[HttpStatusCodeEnum.OK],
          data: data || null, // 如果没有返回数据，返回 null
          timestamp: new Date().toISOString(),
        };
      }),
    );
  }
}
